import axios from 'axios'
import {Message, MessageBox} from 'element-ui'
import {getToken, removeToken, removeLocalUserInfo} from "@/utils/auth";
import Router from "@/router";

// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent
        // 是否需要登录状态
        const loginSymbol = 'loginRequired';
        const loginRequired = config.headers.has(loginSymbol) && config.headers.get(loginSymbol);
        let token = getToken()
        if (token && loginRequired) {
            config.headers['Authorization'] = token
        }
        // 移除自定义请求头（不加此处要报错）
        config.headers.delete(loginSymbol)
        return config
    },
    error => {
        // do something with request error
        console.log(error)
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        // if the custom code is not 200, it is judged as an error.
        const res = response.data
        const code = res.code;

        // 请求成功，系统定义code返回200为请求成功，可自行修改
        if (code === 200) {
            return res;
        }

        // 未登录或登录失效
        if (res.code === 401) {
            MessageBox.confirm("会话已过期，请重新登录", "提示", {
                confirmButtonText: "确定",
                showCancelButton: false,
                type: "warning"
            }).then(() => {
                removeToken();
                removeLocalUserInfo();
                Router.push({path: '/'})
            }).catch(() => {
            });
        } else {
            // 其他错误
            Message.error(res.message);
        }

        return Promise.reject(res)
    },
    error => {
        Message({
            message: error.message,
            type: 'error'
        })
        return Promise.reject(error)
    }
)

export default service
